#!/usr/bin/perl
use strict;
use File::Basename;
use Cwd 'abs_path';
use JNPR::Utils;
use Getopt::Long;

my $opts = {};
GetOptions ($opts, 'svnroot=s', 'workdir=s', 'upload2db=s');

if (!exists $opts->{'svnroot'}) {
    die "Error: $0 : need svnroot\n";
}
my $S       = $opts->{'svnroot'};
JNPR::Utils::set_url($S);

if (!exists $opts->{'workdir'}) {
    die "Error: $0 : need workdir\n";
}
my $workdir = $opts->{'workdir'};

# if (!exists $opts->{'upload2db'}) {
#     die "Error: $0 : need upload2db location\n"
#       . "      e.g.  om\@172.22.18.160:/home/om/public_html/dbqf\n\n"
#       ;
# }
my $workdir = $opts->{'workdir'};

my $running = "$workdir/running.txt";
my $sqlite;
my $bindir  = dirname(abs_path($0));

$ENV{PATH} = ':/opt/CollabNet_Subversion/bin'
           . ':/sbin:/usr/sbin:/bin:/usr/local/sbin'
           . ':/usr/local/bin:/usr/bin:/volume/labtools/bin'
           . ':/volume/buildtools/bin:/volume/sw-tools/bin'
           . ':/usr/ccs/bin'
           ;
if (-e '/usr/local/bin/sqlite3') {
    $sqlite = '/usr/local/bin/sqlite3';
}
elsif (-e '/usr/bin/sqlite3') {
    $sqlite = '/usr/bin/sqlite3';
}
elsif (-e "$bindir/sqlite3-freebsd-captive/sqlite") {
    $sqlite = "$bindir/sqlite3-freebsd-captive/sqlite";
}

my $hostname = `hostname`;
chomp $hostname;
#exit 1 if ($hostname ne 'svl-junos-d047.juniper.net');

if (!-d $workdir) {
    system "mkdir -p $workdir";
}
if (!-d $workdir) {
    print "Cannot mkdir $workdir\n";
    die;
}
chdir $workdir;
grab_running_lock();


my $revmax_repo = `svn info $S|grep Revision:|sed 's/^.* //'`;
chomp $revmax_repo;

if(-f 'db.good') {
    system "cp db.good db";
    system "$sqlite db 'select max(rev) from nodes' >revmax_db.txt";
    my ($nodes_hi_rev, $nodes_lo_rev) = JNPR::Utils::get_counts('db', 'nodes_hi_rev', 'nodes_lo_rev');
    exit 0 if ($nodes_hi_rev == $revmax_repo and $nodes_lo_rev == 0);
}

while (1) {
    my $limit = 100; 
    my $cmd = "perl -I$bindir $bindir/capture-rlog-generic.pl"
            . " --db db"
            . " --svnroot $S"
            . " --limit $limit"
            ;
    my $status = `$cmd`;
    print $status;
    system "perl -I$bindir $bindir/nodes.pl    --db db";               # Extract commit nodes from rlog
    system "perl -I$bindir $bindir/branches.pl --db db --svnroot $S";  # Extract branches from nodes
    system "perl -I$bindir $bindir/merges.pl   --db db --svnroot $S";  # Extract merge info from nodes
    system "$sqlite db .dump >db.sql";
    chomp $status;
    if($status =~ /Revlog captured:\s*(\d+)$/) {
        last if($limit != $1);
    }
    else {
        last;
    }
}

if (-f 'db.good' and -f 'db.good.sql') {
    my @diff = `diff db.good.sql db.sql | grep '<'`;
    if ((scalar @diff == 1) || (scalar @diff == 2)) {
        system "rm db.good; mv db.sql db.good.sql";
        system "$sqlite db.good <db.good.sql";
        if (exists $opts->{'upload2db'}) {
            system "/usr/local/bin/rsync -e ssh -a db.good ".$opts->{'upload2db'};
        }
        # Value is something like om\@172.22.18.160:/home/om/public_html/dbqf
    }
    else {
        print "May be something is wrong\n";
        print "@diff";
    }
}

sub grab_running_lock
{
    exit 1 if (running());
    unlink $running;
    if (-l $running) {
        die "Error: Could not delete $running.\n";
    }
    symlink $$, $running;
    if (!-l $running) {
        die "Error: Could not create symlink $running.\n";
    }
}

sub running
{

    my $oldpid;

    return 0 if (! -l $running);
    $oldpid = readlink $running;
    if ($oldpid !~ /^\d+$/) {
        die "Error: $running does not point to a pid. It should.\n";
    }
    return 1 if (getpgrp($oldpid) != -1);  # It's an active process
    return 0;
}

